package com.example.demo.controller;

import com.example.demo.service.UserService;
import com.example.demo.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录控制
     *
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "login";
    }

    /**
     * 欢迎页面
     *
     * @return
     */
    @RequestMapping("/welcome")
    public String welcome() {
        return "welcome";
    }

    /**
     * 登录校验
     *
     * @param account
     * @param password
     * @param map
     * @return
     */
    @RequestMapping(value = "/login")
    public String checkLogin(HttpServletRequest request, HttpServletResponse response, String account, String password, Map<String, Object> map) {
        User user = userService.findUser(account);
        if (user != null && password.trim().equals(user.getPassword())) {
            request.getSession(true).setAttribute("SESSION_USER", user);
            //登陆成功，跳转主页
            return "index";
        } else {
            request.getSession(true).setAttribute("LOGIN_ERROR", "用户不存在或密码错误.");
            map.put("msg", "用户名密码错误");
            return "login";
        }
    }

    @RequestMapping(value = "/loginout")
    public String checkLogin(HttpServletRequest request, HttpServletResponse response) {
        request.getSession(true).removeAttribute("SESSION_USER");
        return "login";
    }


}
